<template>
  <el-dialog
    v-model="dialogVisible"
    title="节点详情"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="nodeData" class="node-detail">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="节点名称">
          {{ nodeData.nodeName || nodeData.taskName || nodeData.name || '未命名' }}
        </el-descriptions-item>
        <el-descriptions-item label="节点类型">
          {{ getNodeTypeText(nodeData.taskType || nodeData.type) }}
        </el-descriptions-item>
        <el-descriptions-item label="节点状态">
          <el-tag :type="getStatusType(nodeData.status)">
            {{ getStatusText(nodeData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="执行人">
          {{ nodeData.assignee || nodeData.userName || nodeData.approver || nodeData.handler || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ formatDateTime(nodeData.createTime || nodeData.startTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="结束时间">
          {{ formatDateTime(nodeData.completeTime || nodeData.endTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="处理时长" :span="2">
          {{ getDuration(nodeData) }}
        </el-descriptions-item>
        <el-descriptions-item v-if="nodeData.approvalOpinion" label="审批意见" :span="2">
          {{ nodeData.approvalOpinion }}
        </el-descriptions-item>
        <el-descriptions-item v-if="nodeData.description" label="节点描述" :span="2">
          {{ nodeData.description }}
        </el-descriptions-item>
        <el-descriptions-item v-if="nodeData.taskId" label="任务ID" :span="2">
          {{ nodeData.taskId }}
        </el-descriptions-item>
        <el-descriptions-item v-if="nodeData.taskDefinitionKey" label="任务定义Key" :span="2">
          {{ nodeData.taskDefinitionKey }}
        </el-descriptions-item>
        <el-descriptions-item v-if="nodeData.priority" label="优先级" :span="2">
          <el-tag :type="getPriorityType(nodeData.priority)">
            {{ getPriorityText(nodeData.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="nodeData.dueDate" label="到期时间" :span="2">
          {{ formatDateTime(nodeData.dueDate) }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    
    <div v-else class="no-data">
      <Icon icon="ant-design:exclamation-circle-outlined" />
      <p>暂无节点数据</p>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button 
        v-if="showProcessButton && !isStartOrEndNode" 
        type="primary" 
        @click="handleProcess"
      >
        处理任务
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import Icon from '@/components/Icon/Icon.vue'

// 引入统一的夜间模式样式
import '../styles/dark-theme.css'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  nodeData: {
    type: Object,
    default: null
  },
  showProcessButton: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'process', 'close'])

// 节点数据
const nodeData = ref(null)

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 监听节点数据变化
watch(() => props.nodeData, (newData) => {
  if (newData) {
    nodeData.value = newData
  }
}, { deep: true })

// 获取节点类型文本
const getNodeTypeText = (nodeType) => {
  const typeMap = {
    'startEvent': '开始事件',
    'StartEvent': '开始事件',
    'START_EVENT': '开始事件',
    'endEvent': '结束事件',
    'EndEvent': '结束事件',
    'END_EVENT': '结束事件',
    'userTask': '用户任务',
    'UserTask': '用户任务',
    'USER_TASK': '用户任务',
    'serviceTask': '服务任务',
    'ServiceTask': '服务任务',
    'SERVICE_TASK': '服务任务',
    'exclusiveGateway': '排他网关',
    'ExclusiveGateway': '排他网关',
    'EXCLUSIVE_GATEWAY': '排他网关',
    'parallelGateway': '并行网关',
    'ParallelGateway': '并行网关',
    'PARALLEL_GATEWAY': '并行网关',
    'inclusiveGateway': '包容网关',
    'InclusiveGateway': '包容网关',
    'INCLUSIVE_GATEWAY': '包容网关'
  }
  
  return typeMap[nodeType] || nodeType
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const priorityMap = {
    'HIGH': 'danger',
    'MEDIUM': 'warning',
    'LOW': 'info'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const priorityMap = {
    'HIGH': '高',
    'MEDIUM': '中',
    'LOW': '低'
  }
  return priorityMap[priority] || priority
}

// 格式化日期时间
const formatDateTime = (time) => {
  if (!time) return '-'
  try {
    // 如果是LocalDateTime格式的字符串，需要特殊处理
    if (typeof time === 'string' && time.includes('T')) {
      // 处理LocalDateTime格式：2025-07-31T15:51:59
      const date = new Date(time)
      if (isNaN(date.getTime())) {
        // 如果解析失败，尝试其他格式
        return time
      }
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    } else {
      // 处理其他格式
      const date = new Date(time)
      if (isNaN(date.getTime())) {
        return '-'
      }
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
  } catch (error) {
    console.error('格式化日期时间失败:', error, time)
    return '-'
  }
}

// 计算处理时长
const calculateDuration = (startTime, endTime) => {
  if (!startTime) return '-'
  
  try {
    const start = new Date(startTime)
    const end = endTime ? new Date(endTime) : new Date()
    const diff = end.getTime() - start.getTime()
    
    if (diff < 0) return '-'
    
    const seconds = Math.floor(diff / 1000)
    const minutes = Math.floor(seconds / 60)
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)
    
    if (days > 0) {
      return `${days}天${hours % 24}小时`
    } else if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟`
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds % 60}秒`
    } else {
      return `${seconds}秒`
    }
  } catch (error) {
    return '-'
  }
}

// 提取处理时长
const extractDuration = (description) => {
  if (!description) return null
  // 匹配 "处理时长: X天X小时" 或 "处理时长: X小时X分钟" 或 "处理时长: X分钟X秒" 或 "处理时长: X秒"
  const match = description.match(/处理时长: (.+)/)
  if (match && match[1]) {
    return match[1]
  }
  return null
}

// 获取处理时长
const getDuration = (nodeData) => {
  // 优先从description中提取
  const extractedDuration = extractDuration(nodeData.description)
  if (extractedDuration) {
    return extractedDuration
  }
  
  // 计算处理时长
  const startTime = nodeData.createTime || nodeData.startTime
  const endTime = nodeData.completeTime || nodeData.endTime
  return calculateDuration(startTime, endTime)
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'COMPLETED': 'success',
    'ACTIVE': 'primary',
    'PENDING': 'warning',
    'WAITING': 'info',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'COMPLETED': '已完成',
    'ACTIVE': '进行中',
    'PENDING': '待处理',
    'WAITING': '等待中',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 判断是否为开始或结束节点
const isStartOrEndNode = computed(() => {
  const taskType = nodeData.value?.taskType
  const nodeName = nodeData.value?.nodeName
  const taskDefinitionKey = nodeData.value?.taskDefinitionKey
  
  // 根据节点类型判断
  if (taskType === 'startEvent' || taskType === 'endEvent') {
    return true
  }
  
  // 根据节点名称判断
  if (nodeName && (nodeName.includes('开始') || nodeName.includes('结束'))) {
    return true
  }
  
  // 根据任务定义Key判断
  if (taskDefinitionKey && (taskDefinitionKey.includes('start') || taskDefinitionKey.includes('end'))) {
    return true
  }
  
  return false
})

// 处理任务
const handleProcess = () => {
  emit('process', nodeData.value)
}

// 关闭弹窗
const handleClose = () => {
  emit('close')
}
</script>

<style scoped>
.node-detail {
  padding: 10px 0;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 60px 0;
}

.no-data :deep(svg) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ccc;
}

.no-data p {
  margin: 0;
  font-size: 14px;
}

/* 夜间模式支持 */
:deep(.dark) .no-data {
  color: #666;
}

:deep(.dark) .no-data :deep(svg) {
  color: #555;
}
</style> 